1470D - Strange Housing - CodeForces Solution


constructive algorithms dfs and similar graph matchings graphs greedy *2200

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
using namespace std;
const int MAXN = 3e5 + 3 , MAXM = 3e5 + 3;
struct Edge{
	int To , Next;
}e[MAXM * 2];
int Head[MAXN] , CntEdge;
inline void AddEdge(int u , int v){
	++CntEdge;
	e[CntEdge].To = v;
	e[CntEdge].Next = Head[u];
	Head[u] = CntEdge;
}
int N , M;
queue < int > q;
int vis[MAXN] , used[MAXN];
void bfs(int s) {
	for(int i =1 ; i <= N ; i++) used[i] =0 , vis[i] = 0;
	vis[s] = 1;
	q.push(s);
	while(q.size()) {
		int tmp = q.front();
		q.pop();
		if(used[tmp]) continue;
		used[tmp] = 1;
		for(int i = Head[tmp] ; ~i ; i = e[i].Next) {
			int to = e[i].To;
			if(!used[to]) {
				if(vis[tmp] == 1) {
					vis[to] = -1;
					q.push(to);
				}else {
					if(vis[to] == 0) vis[to] = 1;
					q.push(to);
				}
			}
		}
	}
	int cnt = 0;
	for(int i = 1 ; i <=N ; i++) {
		if(used[i] == 0) {
			puts("NO");
			return ; 
		}
		if(vis[i] == 1) cnt++;
	}
	puts("YES");
	printf("%d\n" , cnt);
	for(int i = 1 ; i <= N ; i++) {
		if(vis[i] == 1) printf("%d " , i);
	}puts("");
	
}
int T;
int main(){
	scanf("%d" , &T);
	while(T--){
		CntEdge = -1;
		scanf("%d %d" , &N , &M);
		for(int i = 1 ; i <= N ; i++) Head[i] = -1;
		for(int i = 1 , u , v; i <= M ; i++) {
			scanf("%d %d" , &u , &v);
			AddEdge(u , v);AddEdge(v , u);
		}	
		bfs(1);
	}
}
	   	 			 			         	      	


Comments

Submit
0 Comments
More Questions

1663D - Is it rated - 3
1311A - Add Odd or Subtract Even
977F - Consecutive Subsequence
939A - Love Triangle
755A - PolandBall and Hypothesis
760B - Frodo and pillows
1006A - Adjacent Replacements
1195C - Basketball Exercise
1206A - Choose Two Numbers
1438B - Valerii Against Everyone
822A - I'm bored with life
9A - Die Roll
1430B - Barrels
279B - Books
1374B - Multiply by 2 divide by 6
1093B - Letters Rearranging
1213C - Book Reading
1468C - Berpizza
1546B - AquaMoon and Stolen String
1353C - Board Moves
902A - Visiting a Friend
299B - Ksusha the Squirrel
1647D - Madoka and the Best School in Russia
1208A - XORinacci
1539B - Love Song
22B - Bargaining Table
1490B - Balanced Remainders
264A - Escape from Stones
1506A - Strange Table
456A - Laptops